package cn.kgc.controller;

import cn.kgc.mapper.AppInfoMapper;
import cn.kgc.mapper.AppVersionMapper;
import cn.kgc.pojo.*;
import cn.kgc.service.BackUserService;
import cn.kgc.util.Constants;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/info")
public class AppInfoController {
    @Resource
    private BackUserService backUserService;
    @Resource
  private AppInfoMapper appInfoMapper;

    private static final Logger log=Logger.getLogger(AppInfoController.class);

    @RequestMapping("/show")
    public  String queryAllApp(@RequestParam(value = "pageNumer",
            defaultValue = "1") String pageNumber,
                               @RequestParam(value = "querySoftwareName",required = false) String querySoftwareName,
                               @RequestParam(value = "checkFlat",required = false) String checkFlat,
                               @RequestParam(value = "queryCategoryLevel1",required = false) String queryLevel1,
                               @RequestParam(value = "queryCategoryLevel2",required = false) String queryCategoryLevel2,
                               @RequestParam(value = "queryCategoryLevel3",required = false) String queryCategoryLevel3,
                               @RequestParam(value = "index",required = false)String index,
                               HttpSession session ){
        int pagesize=4;

        //根据传入的页码数，计算出应该从第几条用户信息开始显示
        int beginIndex=(Integer.parseInt(pageNumber)-1)*pagesize;

        //计算一共有多少数据
        int taotalCount=backUserService.totalCount(querySoftwareName,checkFlat,
                queryLevel1,queryCategoryLevel2,queryCategoryLevel3);
        //根据一共的数据和每页现实的数据去计算一共要分成多少页
        int tataoPage=taotalCount%pagesize>0?taotalCount/pagesize+1:taotalCount/pagesize;
        //调用查询所有的方法，返回的是一个Appinfo类型的list集合
        List<AppInfo> queryAllList=backUserService.queryALLApp(beginIndex,pagesize,
                querySoftwareName,checkFlat,queryLevel1,queryCategoryLevel2,queryCategoryLevel3);

        //定义一个map集合 用来存储需要传送到前端的数据
        Map<String,Object> map=new HashMap();
        //查询所有的内容
        map.put("queryallApp1",queryAllList);
        //一共的数据条数
        map.put("totalCount",taotalCount);
        //一共多少页数
        map.put("taotalPage",tataoPage);
        //页码
        map.put("pageNum",pageNumber);
        //模糊查询的条件传出去，用来继续选择页数
        map.put("querySoftwareName",querySoftwareName);
        map.put("checkFlat",checkFlat);
        map.put("queryCategoryLevel1",queryLevel1);
        map.put("queryCategoryLevel2",queryCategoryLevel2);
        map.put("queryCategoryLevel3",queryCategoryLevel3);
        //错误信息
        map.put("index",index);

        session.setAttribute("pageResult",map);

        return "developer/appinfolist";
    }
    @RequestMapping("/appAdd")
    public String appAdd(){
        return "developer/appinfoadd";
    }
    @RequestMapping("/forAppAdd")
    public  String forAppAdd(AppInfo appInfo, HttpSession session, HttpServletRequest request,
                             Model model,@RequestParam(value = "createdBy",required = false) int creaateBy,
                             @RequestParam(value = "a_logoPicPath", required = false) MultipartFile attach) throws Exception {


        String logoPicPath = null;
        String logoLocPath = null;
        if (!attach.isEmpty()) {

            String path = request.getSession().getServletContext().getRealPath("statics" + "/" + "uploadfiles");

            String oldFileName = attach.getOriginalFilename();//原文件名

            String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
            //上传大小不得超过500000  (50k)
            int filesize = 500000;

            if (attach.getSize() > filesize) {
                //错误提示
                request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_4);
                return "developer/appinfoadd";
            } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jepg") || prefix.equalsIgnoreCase("pneg")) {//上传图片格式
                String fileName = appInfo.getAPKName() + ".jpg";//上传LOGO图片命名:apk名称.apk
                File targetFile = new File(path, fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_2);
                    return "developer/appinfoadd";
                }
                logoPicPath = request.getContextPath() + "/statics/uploadfiles/" + fileName;
                logoLocPath = path + File.separator + fileName;
            } else {
                request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_3);
                return "developer/appinfoadd";
            }
        }
        appInfo.setCreatedBy(creaateBy);
        appInfo.setCreationDate(new Date());
        appInfo.setLogoPicPath(logoPicPath);
        appInfo.setLogoLocPath(logoLocPath);
        appInfo.setStatus(1);
        int i = appInfoMapper.add(appInfo);

        if (i>0){

         return "developer/appinfolist";
        }else {

           session.setAttribute("errormessage","添加错误");

            return "devaloper/appinfoadd";
        }

       }

    }

